package com.xuyuan.concurrent.lock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CacheSystem {
    private final Map<String, String> cache = new HashMap<>();

    //读写锁，读读可不互斥，读写互斥，写写互斥，保证读一致，提高并发
    private final ReadWriteLock lock = new ReentrantReadWriteLock();

    // 读取数据的方法
    public String read(String key, long timeout, TimeUnit unit) throws InterruptedException {
        if (lock.readLock().tryLock(timeout, unit)) {
            try {
                return cache.get(key);
            } finally {
                lock.readLock().unlock(); // 释放读锁
            }
        } else {
            // 超时未获取到读锁，可以选择抛出异常或执行其他逻辑
            throw new InterruptedException("Unable to acquire read lock within specified timeout");
        }
    }

    // 写入数据的方法
    public void write(String key, String value, long timeout, TimeUnit unit) throws InterruptedException {
        if (lock.writeLock().tryLock(timeout, unit)) {
            try {
                cache.put(key, value);
            } finally {
                lock.writeLock().unlock(); // 释放写锁
            }
        } else {
            // 超时未获取到写锁，可以选择抛出异常或执行其他逻辑
            throw new InterruptedException("Unable to acquire write lock within specified timeout");
        }
    }

    public static void main(String[] args) {
        CacheSystem cache = new CacheSystem();

        // 写入数据
        new Thread(() -> {
            try {
                cache.write("key1", "value1", 15, TimeUnit.SECONDS);
                System.out.println(Thread.currentThread().getName() + " 写入 key1");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // 读取数据
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try {
                    String value = cache.read("key1", 15, TimeUnit.SECONDS);
                    System.out.println(Thread.currentThread().getName() + " 读取 key1: " + value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
